const evn = require("../../utils/http/evn")
const { apiGetMyCollectPublic, apiDeleteMyCollectPublic } = require('../../utils/http/api')
// pages/members/fav.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgBaseUrl: evn.dev.imgUrl,
    tabList: [
  { label: '高升本', value: 0, id: 1 },
  { label: '本升硕', value: 1, id: 2 },
  { label: '专升硕', value: 2, id: 3 },
  { label: '硕升博', value: 3, id: 4 },
  { label: '专升本', value: 4, id: 5 }
    ],
    currentTab: 0,
    schoolList: [],
    navbarHeight: 88 ,// 默认值，后续动态设置
    showToast:false,
    showSuccessToast: false,
    pendingUnstarIndex: -1
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const menuButton = wx.getMenuButtonBoundingClientRect ? wx.getMenuButtonBoundingClientRect() : null;
    if (menuButton) {
      // 顶部安全区+胶囊高度+22px
      const navbarHeight = menuButton.top + menuButton.height-16 ;
      this.setData({
        navbarHeight,
        capsuleTop: menuButton.top,
        capsuleHeight: menuButton.height
      });
    }
    this.fetchSchoolList(1); // 默认高升本
  },
  
    //过滤html标签
  filterHtmlTags(html) {
    if (!html) return '';
    return html.replace(/<[^>]+>/g, '').replace(/&nbsp;/g, ' ').trim();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    if (this.successToastTimer) {
      clearTimeout(this.successToastTimer);
      this.successToastTimer = null;
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  onTabChange(e) {
    const index = e.currentTarget.dataset.index;
    const id = this.data.tabList[index].id;
    this.setData({ currentTab: index });
    this.fetchSchoolList(id);
  },
  fetchSchoolList(id) {
    // 从本地缓存获取userId
    const userInfo = wx.getStorageSync('userInfo') || {};
    const userId = userInfo.id;
    if (!userId) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      return;
    }
    apiGetMyCollectPublic({ userId, eduPlanId: id }).then(res => {
      let list = [];
      if (Array.isArray(res)) {
        list = res;
      } else if (res && Array.isArray(res.data)) {
        list = res.data;
      } else if (res && res.data && Array.isArray(res.data.list)) {
        list = res.data.list;
      }
      // placeId映射文本
      const placeMap = { 1: '韩国', 2: '西班牙', 3: '新加坡', 4: '中外合办', 5: '港澳专区' };
      // 在获取schoolList数据后（如setData前或接口回调后）做desc字段截断
      if (Array.isArray(list)) {
        list = list.map(item => {
          let desc = item.desc || '';
          if (desc.length >18) desc = desc.slice(0, 18) + '...';
          return { ...item, desc };
        });
      }
      this.setData({
        schoolList: list.map(item => {
          // 兼容logo、pics、avatar三种字段，优先logo，其次pics（字符串或数组），最后avatar
          let logo = '';
          if (item.logo) {
            logo = item.logo;
          } else if (item.pics) {
            if (Array.isArray(item.pics)) {
              logo = item.pics[0] || '';
            } else if (typeof item.pics === 'string' && item.pics.includes(',')) {
              logo = item.pics.split(',')[0];
            } else {
              logo = item.pics;
            }
          } else if (item.avatar) {
            logo = item.avatar;
          }
           item.intro = this.filterHtmlTags(item.intro);
          // desc字段截断22字，优先item.desc，否则用item.intro
          let desc = item.desc || item.intro || '';
          if (desc.length > 18) desc = desc.slice(0, 18) + '...';
          return {
            id: item.wechatUserStarId,
            img: item.avatar,
            name: item.name,
            tag: this.getPlanName(item.eduPlanId),
            city: item.cityName || '',
            desc: desc,
            fav: true,
            schoolId: item.schoolId || item.id || ''
          };
        })
      });
    });
  },
  getPlanName(eduPlanId) {
    eduPlanId = Number(eduPlanId); // 保证是数字
    const map = { 1: '高升本', 2: '本升硕', 3: '专升硕', 4: '硕升博', 5:'专升本' };
    return map[eduPlanId] || '';
  },
  /**
   * 收藏心形按钮点击事件
   */
  onToggleFav(e) {
   const index = Number(e.currentTarget.dataset.index);
   this.setData({
     showToast: true,
     pendingUnstarIndex: isNaN(index) ? -1 : index
   })
  },
  queding(e){
    const idxFromEvent = e && e.currentTarget && typeof e.currentTarget.dataset.index !== 'undefined'
      ? Number(e.currentTarget.dataset.index) : undefined;
    const index = typeof idxFromEvent === 'number' ? idxFromEvent : Number(this.data.pendingUnstarIndex);
    const { schoolList } = this.data;
    if (isNaN(index) || index < 0 || index >= (schoolList?.length || 0)) {
      this.setData({ showToast: false, pendingUnstarIndex: -1 });
      wx.showToast({ title: '操作无效', icon: 'none' });
      return;
    }
    const item = schoolList[index];
    // 先变灰
    schoolList[index].fav = false;
    this.setData({ schoolList });
    // 调用删除收藏接口
    apiDeleteMyCollectPublic({ id: item.id }).then(res => {
      // 删除成功后移除该项
      const newList = this.data.schoolList.filter((_, i) => i !== index);
      this.setData({ schoolList: newList, showToast: false, pendingUnstarIndex: -1, showSuccessToast: true });
      if (this.successToastTimer) {
        clearTimeout(this.successToastTimer);
      }
      this.successToastTimer = setTimeout(() => {
        this.setData({ showSuccessToast: false });
        this.successToastTimer = null;
      }, 2000);
    }).catch(() => {
      // 失败回滚
      schoolList[index].fav = true;
      this.setData({ schoolList, showToast: false, pendingUnstarIndex: -1 });
      wx.showToast({ title: '取消收藏失败', icon: 'none' });
    });
  },

  quxiao(){
    this.setData({
      showToast: false,
      pendingUnstarIndex: -1
    })
  },

  // 点击院校卡片，跳转到院校详情
  onSchoolCardTap(e) {
    const index = e.currentTarget.dataset.index;
    const item = this.data.schoolList[index];
    if (!item || !item.schoolId) {
      wx.showToast({ title: '缺少schoolId', icon: 'none' });
      return;
    }
    wx.navigateTo({
      url: '/pages/schools/schools?schoolId=' + item.schoolId,
    });
  },
  goBack() {
    wx.navigateBack({
      delta: 1
    })
  },
})